package io.github.yotta.export.web.controller;

import io.github.yotta.common.api.exception.ServiceException;
import io.github.yotta.common.api.model.ApiPageRequest;
import io.github.yotta.export.core.enums.DataExportStatus;
import io.github.yotta.export.core.model.DataExportResult;
import io.github.yotta.export.web.iface.ExportTaskCache;
import io.github.yotta.export.web.iface.SpringExcelDataExporter;
import io.github.yotta.export.web.manager.ExcelExportManager;
import io.github.yotta.export.web.manager.ExcelExporterRegister;
import io.github.yotta.export.web.model.ExportTaskResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.UUID;

/**
 * @author yotta
 * @date 2025/4/27
 */
@RequiredArgsConstructor
@Slf4j
@Component
public class ExcelExportProcessor {

    private final ExcelExportManager excelExportManager;
    private final ExcelExporterRegister excelExporterRegister;
    private final ExportTaskCache exportTaskCache;

    public ExportTaskResult process(String name, String exportParamJson) {
        log.info("process name:{}, exportParamJson:{}", name, exportParamJson);
        SpringExcelDataExporter<?, ?> exporter = excelExporterRegister.get(name);
        Objects.requireNonNull(exporter);
        ApiPageRequest r = getExportParam(name, exportParamJson);
        DataExportResult exportResult = excelExportManager.exportExcel(name, r);
        if (exportResult.getStatus().equals(DataExportStatus.ERROR.getCode())) {
            throw new ServiceException(exportResult.getMessage());
        }
        return new ExportTaskResult(name, name + "-" + UUID.randomUUID(), exportResult);
    }

    public ExportTaskResult processAsync(String name, String exportParamJson) {
        log.info("process async name:{}, exportParamJson:{}", name, exportParamJson);
        String taskId = name + "-" + UUID.randomUUID();
        ExportTaskResult exportTaskResult = new ExportTaskResult(name, taskId, null);
        exportTaskCache.add(taskId, exportTaskResult);
        SpringExcelDataExporter<?, ?> exporter = excelExporterRegister.get(name);
        Objects.requireNonNull(exporter);
        ApiPageRequest exportParam = getExportParam(name, exportParamJson);
        excelExportManager.exportExcelAsync(name, exportParam,
                result -> {
                    exportTaskResult.setTaskId(taskId);
                    exportTaskCache.add(taskId, exportTaskResult);
                });
        return exportTaskResult;
    }

    private ApiPageRequest getExportParam(String name, String exportParamJson) {
        SpringExcelDataExporter<?, ?> exporter = excelExporterRegister.get(name);
        return exporter.paramConvert().convert(exportParamJson);
    }
}
